<template>
  <div>
    <div class="search">
      <input type="text" v-model="keyworld" class="search-input" placeholder="请输入城市名或拼音">
    </div>
    <!-- 搜索数据展示区,当搜索框有输入内容 的时候才显示 -->
    <div class="search-content" ref="search" v-show="keyworld">
      <ul>
        <li class="search-item border-bottom" v-for="item of list" :key="item.id"
        @click="handleCityClick(item.name)">{{item.name}}</li>
        <!-- 搜索内容匹配不到数据 或者没有输入内容的时候，显示提示文字 -->
        <li class="search-item border-bottom" v-show="hasNoData">没有找到匹配数据</li>
      </ul>
    </div>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import Bscroll from 'better-scroll'
export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keyworld: '',
      list: [], // 存放城市搜索展示数据
      timer: null
    }
  },
  computed: { // 计算属性
    hasNoData () {
      return !this.list.length
    }
  },
  watch: {
    keyworld () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyworld) { // 当搜索框的内容被清空，下面的搜索结果也被清空
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.cities) {
          this.cities[i].forEach((val) => { // 搜索框输入城市名或者拼音，将包含的结果返回
            if (val.spell.indexOf(this.keyworld) > -1 || val.name.indexOf(this.keyworld) > -1) {
              result.push(val)
            }
          })
        }
        this.list = result
      }, 100)
    }
  },
  methods: {
    // handleCityClick (city) { // 点击改变城市，并且页面跳转到首页
    //   this.$store.commit('changeCity', city)
    //   this.$router.push('/')
    // }
    handleCityClick (city) {
      this.changeCity(city)
      this.$router.push('/')
    },
    ...mapMutations(['changeCity'])
  },
  mounted () { // 给搜索结果展示添加滚动条
    this.scroll = new Bscroll(this.$refs.search)
  }
}

</script>

<style lang="stylus" scoped>
  @import '~styles/varibles.styl'
  .search
    height .72rem
    padding 0 .1rem
    background $bgColor

    .search-input
      box-sizing border-box
      width 100%
      height .62rem
      padding 0 .1rem
      line-height .62rem
      text-align center
      border-radius .06rem
      color #666
  .search-content
    overflow hidden
    z-index 1
    position absolute
    top 1.58rem
    left 0
    right 0
    bottom 0
    background #eee
    .search-item
      line-height .62rem
      padding-left .2rem
      color #666
      background #fff
</style>
